﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LSQL; // 确保引用了正确的命名空间

namespace Shopfloormanagement.Forms
{
    public partial class regForm : Form
    {
        public static regForm instance = new regForm();  
        public regForm()
        {
            instance = this;
            InitializeComponent();
            SetupEventHandlers();
            LoadDepartments();
            LoadFactory();
            LoadRoles();
        }

        private void LoadDepartments()
        {
            try
            {
                string Table = $"[{SystemInfo.db}].[dbo].[Departments]";
                DataTable departmentsTable = SQL.ReturnDataTable3(SystemInfo.SQL,Table,"Del_tag = 0");

                if (departmentsTable != null && departmentsTable.Rows.Count > 0)
                {
                    cboxDepartment.DisplayMember = "DepartmentName";
                    cboxDepartment.ValueMember = "ID";
                    cboxDepartment.DataSource = departmentsTable;
                }
                else
                {
                    MessageBox.Show("未找到部门信息。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载部门信息时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadDepartmentsCondition()
        {
            try
            {
                string Table = $"[{SystemInfo.db}].[dbo].[Departments]";
                DataTable departmentsTable = SQL.ReturnDataTable3(SystemInfo.SQL, Table, $"Del_tag = 0 and FactoryID = {cmbFactory.SelectedValue}");

                if (departmentsTable != null && departmentsTable.Rows.Count > 0)
                {
                    cboxDepartment.DisplayMember = "DepartmentName";
                    cboxDepartment.ValueMember = "ID";
                    cboxDepartment.DataSource = departmentsTable;
                }
                else
                {
                    MessageBox.Show("未找到部门信息。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载部门信息时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadFactory()
        {
            DataTable dt1 = SQL.ReturnDataTable3(SystemInfo.SQL, "Factories","Del_tag = 0");
            if (dt1.Rows.Count > 0)
            {
                cmbFactory.DisplayMember = "FactoryName";
                cmbFactory.ValueMember = "ID";
                cmbFactory.DataSource = dt1;
            }
        }

        private void LoadRoles()
        {
            DataTable dt1 = SQL.ReturnDataTable1(SystemInfo.SQL, "Roles");
            if (dt1.Rows.Count > 0)
            {
                //cboxRole.DisplayMember = "RoleName";
                //cboxRole.ValueMember = "ID";
                //cboxRole.DataSource = dt1;
            }
        }

        private void SetupEventHandlers()
        {
            txtFirstName.TextChanged += InputField_Changed;
            txtLastName.TextChanged += InputField_Changed;
            txtEmail.TextChanged += InputField_Changed;
            txtPhone.TextChanged += InputField_Changed;
            cboxDepartment.SelectedIndexChanged += InputField_Changed;

            // 为复选框添加特定的事件处理程序

        }

        private void InputField_Changed(object sender, EventArgs e)
        {
            CheckAllFieldsFilled();
        }

        private void CheckAllFieldsFilled()
        {
            bool allFilled = !string.IsNullOrWhiteSpace(txtFirstName.Text) &&
                             !string.IsNullOrWhiteSpace(txtLastName.Text) &&
                             !string.IsNullOrWhiteSpace(txtEmail.Text) &&
                             !string.IsNullOrWhiteSpace(txtPhone.Text) &&
                             cboxDepartment.SelectedIndex != -1;

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("您确定要取消注册吗？", "确认取消", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                this.Close();
            }
        }

        //检测用户名是否注册
        private void uiButton1_Click(object sender, EventArgs e)
        {
            string loginName = txtLogin.Text;
            try
            {
                int res = LSQL.SQL.ReturnRowsCount3(SystemInfo.SQL, "[dbo].[Employees]", $"loginName = '{loginName}'");
                if (res == 0)
                {
                    //数据库无用户
                    loginCheck.Visible = true;
                    loginCheck.Symbol = 61452;
                    loginCheck.SymbolColor = Color.LimeGreen;
                }
                else if (res > 0)
                {
                    //数据库有用户
                    loginCheck.Visible = true;
                    loginCheck.Symbol = 61453;
                    loginCheck.SymbolColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error message: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                LSQL.SQL.con.Close();
            }
        }

        private void txtConfirm_TextChanged(object sender, EventArgs e)
        {
            string pwd = txtPwd.Text;
            if (pwd == txtConfirm.Text)
            {
                //检测密码是否一致
                pwdCheck.Visible = true;
                pwdCheck.Symbol = 61452;
                pwdCheck.SymbolColor = Color.LimeGreen;
            }
            else
            {
                pwdCheck.Visible = true;
                pwdCheck.Symbol = 61453;
                pwdCheck.SymbolColor = Color.Red;
            }
        }

        // 判断字符是否为中文
        private bool IsChinese(string input)
        {
            foreach (char c in input)
            {
                if (c >= 0x4E00 && c <= 0x9FFF)
                    return true;
            }
            return false;
        }

        // 判断字符是否为英文
        private bool IsEnglish(string input)
        {
            foreach (char c in input)
            {
                if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
                    return true;
            }
            return false;
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            //if (ValidateAllFields())
            //{
            //    if (RegisterUser())
            //    {
            //        MessageBox.Show("注册成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        this.Close();
            //    }
            //    else
            //    {
            //        MessageBox.Show("注册失败，请稍后重试。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    }
            //}
            //else
            //{
            //    MessageBox.Show("请确保所有信息填写正确。", "信息不完整", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //}
            if (txtFirstName.Text != "")
            {
                if (txtLastName.Text != "")
                {
                    if (cboxDepartment.Text != "")
                    {
                        if (cmbFactory.Text != "")
                        {
                            if (txtLogin.Text != "")
                            {
                                if (txtPwd.Text != "")
                                {
                                    if (txtConfirm.Text != "")
                                    {
                                        if (txtPwd.Text == txtConfirm.Text)
                                        {
                                            if (true)
                                            {
                                                DataTable dt1 = SQL.ReturnDataTable3(SystemInfo.SQL, "Employees", "LoginName='" + txtLogin.Text + "' or Email='" + txtEmail.Text + "' or PhoneNumber='" + txtPhone.Text + "'");
                                                if (dt1.Rows.Count == 0)
                                                {
                                                    //判断输入是中文还是英文
                                                    string full = string.Empty;
                                                    bool isInput1Chinese = IsChinese(txtFirstName.Text);
                                                    bool isInput2Chinese = IsChinese(txtLastName.Text);
                                                    bool isInput1English = IsEnglish(txtFirstName.Text);
                                                    bool isInput2English = IsEnglish(txtLastName.Text);

                                                    if (isInput1Chinese && isInput2Chinese) // 都是中文
                                                    {
                                                        full = txtLastName.Text + txtFirstName.Text; // 拼接顺序为 21
                                                    }
                                                    else if (isInput1English && isInput2English) // 都是英文
                                                    {
                                                        full = txtFirstName.Text + " " + txtLastName.Text; // 拼接顺序为 12
                                                    }
                                                    else // 一个中文，一个英文
                                                    {
                                                        full = txtLastName.Text + txtFirstName.Text; // 拼接顺序为 21
                                                    }
                                                    string salt = GenerateSalt();
                                                    string FirstName = "'" + txtFirstName.Text + "'";
                                                    string LastName = "'" + txtLastName.Text + "'";
                                                    string Email = "'" + txtEmail.Text + "'";
                                                    string PhoneNumber = "'" + txtPhone.Text + "'";
                                                    string LoginName = "'" + txtLogin.Text + "'";
                                                    string PasswordHash = "'" + HashPassword(txtPwd.Text, salt) + "'";
                                                    object Dep = cboxDepartment.SelectedValue;
                                                    object Fac = cmbFactory.SelectedValue;
                                                    
                                                    string Items = "FirstName,LastName,Email,PhoneNumber,LoginName,PasswordHash,HomeDepartmentID,FactoryID,PasswordSalt,FullName";
                                                    string Values = $"{FirstName},{LastName},{Email},{PhoneNumber},{LoginName},{PasswordHash},{Dep},{Fac},'{salt}','{full}'";
                                                    int a = SQL.Insert(SystemInfo.SQL, "Employees", Items, Values);
                                                    if (a > 0)
                                                    {
                                                        DataTable res = SQL.ReturnDataTable3(SystemInfo.SQL, "Employees", "LoginName='" + txtLogin.Text + "' or Email='" + txtEmail.Text + "' or PhoneNumber='" + txtPhone.Text + "'");
                                                        if (res.Rows.Count > 0)
                                                        {
                                                            int ID = (int)res.Rows[0]["ID"];
                                                            string str = $"INSERT INTO EmployeeDepartments (EmployeeID,DepartmentID,StartDate) VALUES ({ID},{cboxDepartment.SelectedValue},GetDate())";
                                                            int b = SQL.Insert2(SystemInfo.SQL, str);
                                                            if (b > 0)
                                                            {
                                                                MessageBox.Show("注册成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                                                this.Close();
                                                            }
                                                        }
                                                        
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("注册失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                    }
                                                }
                                                else
                                                {
                                                    MessageBox.Show("账号信息重复，请重新输入！\r\n（邮箱？），（移动电话？），（用户名？）", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                }
                                            }
                                            else
                                            {
                                                MessageBox.Show("请选择用户角色", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            }
                                            
                                        }
                                        else
                                        {
                                            MessageBox.Show("两次密码不一致，请重新输入！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("请输入确认密码！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        txtConfirm.Focus();
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("请输入密码！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    txtPwd.Focus();
                                }
                            }
                            else
                            {
                                MessageBox.Show("请输入用户名！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                txtLogin.Focus();
                            }
                        }
                        else
                        {
                            MessageBox.Show("请选择所属工厂！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);                          
                        }                       
                    }
                    else
                    {
                        MessageBox.Show("请选择所属部门！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        cboxDepartment.Focus();
                    }
                }
                else
                {
                    MessageBox.Show("请输入姓！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtLastName.Focus();
                }
            }
            else
            {
                MessageBox.Show("请输入名！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtFirstName.Focus();
            }
        }

        // 生成盐值
        private string GenerateSalt()
        {
            byte[] saltBytes = new byte[16];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(saltBytes);
            }
            return Convert.ToBase64String(saltBytes);
        }

        private string HashPassword(string password, string salt)
        {
            using (var sha256 = System.Security.Cryptography.SHA256.Create())
            {
                var saltedPassword = password + salt;
                var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(saltedPassword));
                return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
            }
        }

        private void cmbFactory_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDepartmentsCondition();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            string salt = GenerateSalt();
            Console.WriteLine(salt);
            Console.WriteLine(HashPassword(txtPwd.Text, salt)); 
        }
    }
}
